//###############
//FILE : RenameCommand.java
//WRITER : Daniel Lowengrub, daniel_i_l, 320687098
//EXERCISE : oop ex3 2011
//DESCRIPTION:
//See below
//###############
package oop.ex3.filemanager;

import oop.ex3.communication.SocketAddress;

/**
 * Implement the RENAME command as specified in the assignment.
 * @author daniel
 */
public class RenameCommand extends ModifyingCommand{

    private static final String RENAME_COMMAND = "RENAME";
    private static final String ABSENT_ERROR = "It is impossible to rename an absent file";
    private static final String EXISTING_ERROR = "It is illegal to use an existing file name as a new name";
    private static final String RENAME_ERROR = "the renaming was unsuccessfull";
    private static final String END_MSG = "Renaming Done";
    private static final int OLDNAME_ARG = 1;
    private static final int NEWNAME_ARG = 2;


    /**
     * Construct a remove command with a connection used for communication with
     * NS.
     * @param connection The connection to use.
     */
    public RenameCommand(NameServerConnection connection) {
        super(RENAME_COMMAND, connection);
    }

    private void notifyNameServer(SocketAddress nameServer, String oldFile, String newFile) {
        notifyNameServerRemoval(nameServer, oldFile);
        notifyNameServerAddition(nameServer, newFile);
    }


    @Override
    public boolean executeCommand(String command) {
        String[] args = command.trim().split(COMMAND_SPACER);
        String oldFile = args[OLDNAME_ARG];
        String newFile = args[NEWNAME_ARG];

        if (!_fileDatabase.hasFile(oldFile)) {
            System.out.println(ABSENT_ERROR);
            return true;
        }

        if (_fileDatabase.hasFile(newFile)) {
            System.out.println(EXISTING_ERROR);
            return true;
        }

        //close upload permissions for this file
        _fileDatabase.setStreamingPermission(oldFile, false);
        //and wait for uploads to finish
        waitForUploads(oldFile);

        //try to rename the file
        if (!_fileDatabase.renameFile(oldFile, newFile)){
            System.out.println(RENAME_ERROR);
            return true;
        }

        //allow uploads again
        _fileDatabase.setStreamingPermission(newFile, true);

        //update nameservers of renaming
        for (SocketAddress nameServer : _nameServers.getAddressList())
            notifyNameServer(nameServer, oldFile, newFile);

        //and finish up
        System.out.println(END_MSG);
        return true;
    }

}
